package org.microservice.auth.service;

import org.apache.commons.lang.StringUtils;
import org.microservice.auth.dao.SysMenuDao;
import org.microservice.auth.dao.SysUserDao;
import org.microservice.auth.entity.UserDetailsImpl;
import org.microservice.common.bean.MenuVo;
import org.microservice.common.bean.RoleVo;
import org.microservice.common.bean.UserVo;
import org.microservice.common.util.CustomRuntimeException;
import org.microservice.common.util.constant.CommonConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: 齐丹枫
 * Date: 2018/6/6
 * Time: 14:39
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysMenuDao sysMenuDao;



    @Override
    public UserDetailsImpl loadUserByUsername(String username) throws UsernameNotFoundException {
        if(StringUtils.isBlank(username)){
            throw  new CustomRuntimeException("用户名不能为空");
        }
        List<MenuVo> sysMenus =  new ArrayList<>();
        UserVo userVo = sysUserDao.findUserByUsername(username);
        /**
         * 对admin进行特殊处理
         */
        if(username.equals(CommonConstant.ADMIN_NAME)){
            HashMap<String, Object> map = new HashMap<>();
            map.put("type",CommonConstant.BUTTON);
            sysMenus =sysMenuDao.selectByMap(map);

        }else{


            if(userVo == null){
                throw new CustomRuntimeException("用户名不存在");
            }


            List<Integer> integers = new ArrayList<>();

            List<RoleVo> roles = userVo.getRoles();
            if(roles != null){
                for (int i = 0; i < roles.size(); i++) {
                    RoleVo roleVo = roles.get(i);
                    if(!roleVo.isDisabled()){
                        integers.add(roleVo.getId());
                    }

                }
            }

            if(integers.size()> 0){
                /**
                 * 只查询角色的按钮权限，用于oauth的权限认证
                 */
                sysMenus = sysMenuDao.findMenusByRoleIds(integers, CommonConstant.BUTTON);

            }
        }

        return new UserDetailsImpl(userVo,sysMenus);

    }
}